package com.bupt.cosmfl.cosmflweb.service.impl;

import com.bupt.cosmfl.cosmflweb.dto.UserLoginDTO;
import com.bupt.cosmfl.cosmflweb.dto.UserRegisterDTO;
import com.bupt.cosmfl.cosmflweb.exception.BusinessException;
import com.bupt.cosmfl.cosmflweb.mapper.UserMapper;
import com.bupt.cosmfl.cosmflweb.model.UserEntity;
import com.bupt.cosmfl.cosmflweb.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public Integer register(UserRegisterDTO dto) {
        UserEntity newUser = new UserEntity();
        BeanUtils.copyProperties(dto, newUser);
        int insertNum;
        try {
            insertNum = userMapper.insert(newUser);
        } catch (Exception e) {
            throw new BusinessException("insert User error:" + e.getMessage());
        }
        return insertNum;
    }

    @Override
    public boolean login(UserLoginDTO dto) {
        Map<String, Object> user = new HashMap<>();
        user.put("username", dto.getUsername());
        user.put("password", dto.getPassword());
        List<UserEntity> userEntities;
        try {
            userEntities = userMapper.selectByMap(user);
        } catch (Exception e) {
            throw new BusinessException("数据库查询发生错误:" + e.getMessage());
        }
        if (CollectionUtils.isEmpty(userEntities)) {
            throw new BusinessException("登录异常，用户名或密码错误！");
        }
        return true;
    }
}
